define(['jquery'], function ($) {
	
	var file_select = $('#file-select');

	// 点击附件上传， 选择要上传的附件
	$('#upload-file').on('click', function (e) {
		if (e.target === this) file_select.click();
	});


	file_select.on('change', function () {
		$('.loading').show();
		var formdata = new FormData($('#upload-form')[0]);

		ajaxPost(formdata).then(function (json) {
                callBack(json);
			}).catch(function (err) {
				console.log('err', err)
				alert('上传失败');
	 			$('.loading').hide();
            });
	});

	
	/**
	 * 上传附件
	 * @param  {[string]} selector    上传附件按钮的class或id,  .select || #select
	 * @param  {[input]} file_elem    文件选择input, $('#file-select')
	 * @param  {[string]} form_selector 上传文件的表单， #upload-form
	 * @return {[type]}               [description]
	 */
	function uploadInit (selector, file_elem, form_selector) {

		$(document).on('click', selector, function (e) {
			file_elem.click();
		})



		file_elem.on('change', function () {
			$('.loading').show();
			var formdata = new FormData($(form_selector)[0]);

			ajaxPost(formdata).then(function (json) {
	                callBack(json);
				}).catch(function (err) {
					console.log('err', err)
					alert('上传失败');
		 			$('.loading').hide();
	            });
		});
	}

	/*
	 * 获取文件后缀名
	 * @param: file => 选中的文件
	 * @return: undefined 或者 文件名
	 */
	function getSuffix (file) {

		var type; // 文件类型

		switch (file){
            case "doc":
            case "txt":
            case "docx":
                type = "doc.png";
                break;
            case "wps":
            case "xls":
            case "xlsx":
                type = "xls.png";
                break;
            case "pdf":
                type = "pdf.png";
                break;
            case "zip":
            case "rar":
                type = "rar.png";
                break;
            case "png":
            case "jpg":
            case "jpeg":
            case "webp":
            case "gif":
                type = "jpg.png";
                break;

            default:
                break;
        }

        return type;

	}


	/*
	 * ajax上传文件
	 * @param: data => ajax提交的数据
	 * @return promise对象
	 */
	function ajaxPost (data) {

	 	return new Promise(function (resolve, reject) {
	 		$.ajax({
	 			url: '/Api/Upload/ajax_uploadFile',
	 			type: 'post',
	 			datatype: 'json',
	 			data: data,
	 			timeout: 30000,
	 			processData: false,
				contentType: false,
	 			success: function (json) {
	 				json.code == 0 ? alert(json.msg) : resolve(json);
	 			},
	 			error: function () {
	 				alert('上传失败');
	 				$('.loading').hide();
	 			}
	 		})
	 	});
	}

	/**
	 * 上传文件成功之后的回调函数
	 * @param: json => ajax返回的数据
	 * @param: data => 被上传文件的信息
	 */
	function callBack (json, data) {
		json = JSON.parse(json)
		var str = 'png/PNG/jpg/JPG/jpeg/JPEG/gif/GIF/webp/WEBP';
			type = json.type_img;
		var hideclass = new RegExp(type).test(str) ? '' : 'hide';

		var tem = '<div class="file-item">' +
                	'<img src="/static/img/' + getSuffix(type) + '" class="icon">' +
                	'<span class="fileName">' + json.filename +'</span>' +
                	'<input type="hidden" name="attachment[]" value="' + json.file_id + '" >' +
                	'<a data-toggle="modal" data-target="#imgModal" data-img="'+ json.url +'" class="color-blue preview '+ hideclass +'">预览</a>' +
                	'<a class="color-blue" href="' + json.url + '">下载</a>' +
                	'<a class="del color-blue">删除</a>' +
                '</div>';
                
        $("#file-container").append(tem);

        $('.loading').hide();
	} 


	// 附件删除
	$('#file-container').on('click', '.del', function () {
		$(this).parents('.file-item').remove();
	});

	// 图片预览
	$('#file-container').on('click', '.preview', function () {
		var imgurl = $(this).data('img');
		$('#imgModal').find('.preview-img').attr('src', imgurl);
	});

	return uploadInit;
});